package bsi.vn.FirstApp;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import bsi.vn.Data.ContractAdapter;
import bsi.vn.Data.ContractData;
import bsi.vn.Data.CookieData;
import bsi.vn.Lib.Consts;
import bsi.vn.Lib.ProcessFunc;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

@SuppressLint("ValidFragment")
public class ATMContractFragment extends Fragment{
	
	private ArrayList<ContractData> contractList = new ArrayList<ContractData>();
	private Context _context;
	private int _iATMId;
	private ListView lvContract;
	
	public ATMContractFragment()
	{}

	public ATMContractFragment(Context context, int atmid) {
		_context = context;
		_iATMId = atmid;
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.fragment_atmcontract, container, false);
		
		lvContract = (ListView) rootView.findViewById(R.id.lvContractList);
		
		myATMContractList myWebFetch = new myATMContractList();
		myWebFetch.execute(String.valueOf(_iATMId));
		
		return rootView;
	}
	
	private class myATMContractList extends AsyncTask<String, String, String> {

		@Override
		protected String doInBackground(String... params) {
			String data = "";
			try {

				data = GetATMTicketList(Integer.parseInt(params[0]));
			} catch (Exception e) {
				e.printStackTrace();
			}
			return data;
		}

		@Override
		protected void onPostExecute(String result) {
			contractList = new ArrayList<ContractData>();
			String loc_arResponse[] = result.split("\\|");
			int loc_iResponseCode = Integer.parseInt(loc_arResponse[0]);
			if (loc_iResponseCode == Consts.RC_LOGOUT) {
				startActivity(new Intent(_context, LoginActivity.class));
				return;
			}
			if (loc_iResponseCode == Consts.RC_ERROR) {
				ProcessFunc.ShowSimpleDialog(_context, "Error", loc_arResponse[1]);
				return;
			}
			
			try {
				JSONArray jArray = new JSONArray(loc_arResponse[1]);
				for (int i = 0; i < jArray.length(); i++) {
					JSONObject json_data = jArray.getJSONObject(i);
					ContractData coData = new ContractData();
					coData.setContractId(json_data.getInt(Consts.SDB_CONTRACTID));
					coData.setContractNo(json_data.getString(Consts.SDB_CONTRACTNO));
					coData.setExpireDate(json_data.getString(Consts.SDB_EXPIREDATE));
					coData.setCustomer(json_data.getString(Consts.SDB_CUSTOMER));
	
					contractList.add(coData);
				}
			} catch (JSONException e) {
				Log.e("test", "Error parsing data " + e.toString());
			}

			lvContract.setAdapter(new ContractAdapter(_context, R.layout.contract_detail_item, contractList));

//			lvTicket.setOnItemClickListener(new OnItemClickListener() {
//				@Override
//				public void onItemClick(AdapterView<?> parent, View view,
//						int position, long id) {
//					int TicketId = ticketData.get(position).getTicketId();
//					Intent i = new Intent(getApplicationContext(),
//							TicketDetailActivity.class);
//					i.putExtra("TicketId", TicketId);
//					startActivity(i);
//				}
//			});
		}

		@Override
		protected void onPreExecute() {
		}

		@Override
		protected void onProgressUpdate(String... text) {
		}
	}

	private String GetATMTicketList(int atmid) {
		InputStream is = null;
		String result = "";
		try {
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(Consts.MAIN_URL);

			CookieData cookie = ProcessFunc.GetCookie(_context);

			List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(4);
			nameValuePair.add(new BasicNameValuePair(Consts.V_FUNC,
					Consts.F_ATMCONTRACTLIST));
			nameValuePair.add(new BasicNameValuePair(Consts.V_USERID, String
					.valueOf(cookie.getUserId())));
			nameValuePair.add(new BasicNameValuePair(Consts.V_COOKIE, cookie
					.getCookie()));
			nameValuePair
					.add(new BasicNameValuePair(Consts.V_ATMID, atmid + ""));

			httppost.setEntity(new UrlEncodedFormEntity(nameValuePair));
			HttpResponse response = httpclient.execute(httppost);
			HttpEntity entity = response.getEntity();
			is = entity.getContent();
		} catch (Exception e) {
			Log.e("log_tag", "Error in http connection " + e.toString());
		}

		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					is, "utf-8"), 16);
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
			is.close();
			result = sb.toString();
		} catch (Exception e) {
			Log.e("test", "Error converting result " + e.toString());
		}
		return result;
	}
}
